package com.tian.utils;

import com.tian.dto.resp.UserInfoRespDto;
import com.tian.enums.ResultCode;
import com.tian.exception.BusinessException;

/**
 * {@code @description:} 用户信息本地缓存工具类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-09-13 23:38
 * {@code @version:} 1.0
 */
public class UserCacheUtil {

    /**
     * 创建ThreadLocal变量
     */
    private static final ThreadLocal<UserInfoRespDto> USER_THREAD_LOCAL = new ThreadLocal<>();

    public static void setUser(UserInfoRespDto user) {
        USER_THREAD_LOCAL.set(user);
    }

    public static UserInfoRespDto getUser() {
        UserInfoRespDto user = USER_THREAD_LOCAL.get();
        if (user == null) {
            throw new BusinessException(ResultCode.UNAUTHORIZED);
        }
        return user;
    }

    public static void clearUser() {
        USER_THREAD_LOCAL.remove();
    }
}